package org.amos.satoken;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.amos.satoken.properties.AuthFilterProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token 代码方式进行配置
 *
 * @author kong
 */
@Slf4j
@AutoConfiguration
@EnableConfigurationProperties(AuthFilterProperties.class)
@RequiredArgsConstructor
public class SaTokenAutoConfiguration implements WebMvcConfigurer {

    private final AuthFilterProperties properties;

    /**
     * 注册 Sa-Token 的拦截器，打开注解式鉴权功能
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册路由拦截器，自定义验证规
        registry.addInterceptor(new SaInterceptor(handler -> {
            SaRouter.match("/**")
                    // 登录前放行接口
                    .notMatch(properties.getExcludePaths())
                    // 登录检查
                    .check(x -> {
                        StpUtil.checkLogin();
                    });
        })).excludePathPatterns(properties.getExcludePaths());
        // 注册注解拦截器
//        registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
    }
}
